﻿using PMS.SANY.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace PMS.SANY.OpenApi
{
    /// <summary>
    /// 请求日志
    /// </summary>
    public class RequestLogFilterAttribute : Attribute, IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<RequestLogFilterAttribute>>();
            var desc = context.ActionDescriptor as Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor;
            var httpContext = context.HttpContext;

            //httpContext.Request.EnableBuffering();
            //var stream = new StreamReader(httpContext.Request.Body);
            //var bodyString = await stream.ReadToEndAsync();
            //httpContext.Request.Body.Seek(0, SeekOrigin.Begin);

            var para = context.ActionArguments.ToJson();
            var ctrlName = desc.ControllerName;
            var actionName = desc.ActionName;
            var method = httpContext.Request.Method;
            var ip = httpContext.Connection.RemoteIpAddress;

            var nextContext = await next();

            var result = nextContext.Result as Microsoft.AspNetCore.Mvc.ContentResult;

            logger.LogInformation($@"Controller:{ctrlName} Action:{actionName} Method:{method} IP:{ip}
Parameters:{para} 
Result:{(result == null ? "" : result.Content)}");
        }
    }
}
